<template>
    <el-row>
        <el-col :span="24">
            <el-card>
                <el-form :inline="true" class="demo-form-inline">
                    <el-form-item>
                        <el-button type="primary" @click="showAddDialog">添加</el-button>
                    </el-form-item>
                    <el-form-item style="float: right;">
                        <el-input v-model="ownerName" placeholder="请输入要搜索的车主姓名" clearable @input="selectByPage(1);" />
                    </el-form-item>
                </el-form>
                <el-table :data="pageInfo.list" stripe style="width: 100%">
                    <el-table-column prop="carId" label="ID" width="50px" />
                    <el-table-column prop="carPlate" label="车牌号" />
                    <el-table-column prop="carAvatar" label="车辆图片">
                        <template #default="scope">
                            <el-avatar shape="square" :size="50"
                                :src="'http://localhost:8080/upload/' + scope.row.carAvatar" />
                        </template>

                    </el-table-column>
                    <el-table-column prop="ownerName" label="车主姓名" />
                    <el-table-column prop="carType" width="80px" label="车辆类型" />
                    <el-table-column prop="carState" width="80px" label="车辆状态">
                        <template #default="scope">
                            <el-tag type="success" v-if="scope.row.carState === 1">在库</el-tag>
                            <el-tag type="danger" v-else="scope.row.carState === 0">离库</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="inTime" label="入库时间" />
                    <el-table-column prop="outTime" label="出库时间" />
                    <el-table-column prop="parkFee" label="停车费" />
                    <el-table-column prop="parkId" label="停车场ID" />
                    <el-table-column label="操作">
                        <template #default="scope">
                            <el-button size="small" type="primary"
                                @click="showUpdateDialog(scope.row.carId)">修改</el-button>
                            <el-popconfirm title="确认删除该车辆信息？" confirm-button-text="确认" cancel-button-text="取消"
                                width="200px" @confirm="deleteCar(scope.row.carId)">
                                <template #reference>
                                    <el-button size="small" type="danger">删除</el-button>
                                </template>
                            </el-popconfirm>
                        </template>
                    </el-table-column>
                </el-table>
                <el-row class="row-bg" justify="center">
                    <el-pagination background layout="prev, pager, next" :page-count="pageInfo.pages"
                        v-model:current-page="pageInfo.pageNum" @update:current-page="selectByPage" style="margin-top: 20px;" />
                </el-row>
            </el-card>
        </el-col>
    </el-row>

    <!-- 添加车辆的对话框开始 -->
    <el-dialog v-model="addDialogShow" title="添加车辆" width="500">
        <el-form>
            <el-form-item label="车牌号" label-width="100px">
                <el-input v-model="carAdd.carPlate" autocomplete="off" />
            </el-form-item>
            <el-form-item label="车主姓名" label-width="100px">
                <el-input v-model="carAdd.ownerName" autocomplete="off" />
            </el-form-item>
            <el-form-item label="车型" label-width="100px">
                <el-input v-model="carAdd.carType" autocomplete="off" />
            </el-form-item>
            <!-- <el-form-item label="车辆状态" label-width="100px">
                <el-input autocomplete="off" />
            </el-form-item> -->
            <el-form-item label="入库时间" label-width="100px">
                <el-date-picker v-model="carAdd.inTime" type="date" placeholder="请选择入库日期" format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD" />
            </el-form-item>
            <el-form-item label="出库时间" label-width="100px">
                <el-date-picker v-model="carAdd.outTime" type="date" placeholder="请选择出库日期" format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD" />
            </el-form-item>
            <el-form-item label="缴费" label-width="100px">
                <el-input v-model="carAdd.parkFee" autocomplete="off" />
            </el-form-item>
            <el-form-item label="停车场" label-width="100px">
                <el-select v-model="carAdd.parkId" placeholder="请选择停车场" style="width: 240px">
                    <el-option v-for="(parklot, index) in parklotList" :key="index" :label="parklot.parkName"
                        :value="parklot.parkId" />
                </el-select>
            </el-form-item>
            <!-- 文件上传组件中的action属性，用于指定上传文件的请求地址，默认是post请求 -->
            <!-- 这里的地址是服务器的controller的请求地址 -->
            <el-form-item label="图片" label-width="100px">
                <el-upload class="avatar-uploader" action="http://localhost:8080/admin/uploadController" name="pic"
                    :headers="headers" :show-file-list="false" :before-upload="beforeAvatarUpload"
                    :on-success="handleAvatarSuccessAdd">
                    <img v-if="imageUrlAdd" :src="imageUrlAdd" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="addDialogShow = false">取消</el-button>
                <el-button type="primary" @click="insert">确认</el-button>
            </div>
        </template>
    </el-dialog>
    <!-- 添加车辆的对话框结束 -->


    <!-- 修改车辆的对话框开始 -->
    <el-dialog v-model="updateDialogShow" title="修改车辆" width="500">
        <el-form>
            <el-form-item label="车牌号" label-width="100px">
                <el-input v-model="carUpdate.carPlate" autocomplete="off" disabled />
            </el-form-item>
            <el-form-item label="车主姓名" label-width="100px">
                <el-input v-model="carUpdate.ownerName" autocomplete="off" />
            </el-form-item>
            <el-form-item label="车型" label-width="100px">
                <el-input v-model="carUpdate.carType" autocomplete="off" />
            </el-form-item>
            <!-- <el-form-item label="车辆状态" label-width="100px">
                <el-input autocomplete="off" />
            </el-form-item> -->
            <el-form-item label="入库时间" label-width="100px">
                <el-date-picker v-model="carUpdate.inTime" type="date" placeholder="请选择入库日期" format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD" />
            </el-form-item>
            <el-form-item label="出库时间" label-width="100px">
                <el-date-picker v-model="carUpdate.outTime" type="date" placeholder="请选择出库日期" format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD" />
            </el-form-item>
            <el-form-item label="缴费" label-width="100px">
                <el-input v-model="carUpdate.parkFee" autocomplete="off" />
            </el-form-item>
            <el-form-item label="停车场" label-width="100px">
                <el-select v-model="carUpdate.parkId" placeholder="请选择停车场" style="width: 240px">
                    <el-option v-for="(parklot, index) in parklotList" :key="index" :label="parklot.parkName"
                        :value="parklot.parkId" />
                </el-select>
            </el-form-item>
            <!-- 文件上传组件中的action属性，用于指定上传文件的请求地址，默认是post请求 -->
            <!-- 这里的地址是服务器的controller的请求地址 -->
            <el-form-item label="图片" label-width="100px">
                <el-upload class="avatar-uploader" action="http://localhost:8080/admin/uploadController" name="pic" :headers="headers"
                    :show-file-list="false" :before-upload="beforeAvatarUpload" :on-success="handleAvatarSuccessUpdate">
                    <img v-if="imageUrlUpdate" :src="imageUrlUpdate" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="updateDialogShow = false">取消</el-button>
                <el-button type="primary" @click="update">确认</el-button>
            </div>
        </template>
    </el-dialog>
    <!-- 修改车辆的对话框结束 -->
</template>

<script setup>
import carApi from '@/api/carApi ';
import parklotApi from '@/api/parklotApi';
import { ElMessage } from 'element-plus';
import { reactive, ref,computed } from 'vue';
import {useTokenStore} from "@/stores/token.js";

const tokenStore = useTokenStore();
//初始化：修改上传图片的地址
const imageUrlUpdate = ref('');
//初始化：修改的对话框的显示状态
const updateDialogShow = ref(false);
//初始化：被修改车辆的信息
const carUpdate = ref({
    carId: '',
    carPlate: '',
    ownerName: '',
    carType: '',
    inTime: '',
    outTime: '',
    parkFee: '',
    parkId: '',
    carAvatar: ''
});
//初始化：请求头
const headers = computed(()=>{
    let token = tokenStore.tokenStr;
    return{
        token
    }
});

//初始化：添加上传图片的地址
const imageUrlAdd = ref('');
//初始化：保存被添加车辆的信息
const carAdd = ref({
    carPlate: '',
    ownerName: '',
    carType: '',
    inTime: '',
    outTime: '',
    parkFee: '',
    parkId: '',
    carAvatar: ''
});
//初始化：保存所有停车场的数据
const parklotList = ref([]);
//初始化：添加的对话框的显示状态
const addDialogShow = ref(false);
//初始化:车主姓名
const ownerName = ref('');
//初始化：分页查询的分页信息
const pageInfo = ref({
    pages: 0,
    pageSize: 0,
    pageNum: 0
});
//定义方法：修改车辆信息
function update() {
    carApi.update(carUpdate.value)
        .then(resp => {
            if (resp.code == 10000) {
                ElMessage.success(resp.msg);
                //隐藏修改的对话框
                updateDialogShow.value = false;
                //刷新表格
                selectByPage(pageInfo.value.pageNum);
            } else {
                ElMessage.error(resp.msg);
            }
        });
}
//定义方法：修改成功图片上传成功的回调
function handleAvatarSuccessUpdate(resp, uploadFile) {
    if (resp.code == 10000) {
        ElMessage.success(resp.msg);
        imageUrlUpdate.value = "http://localhost:8080/upload/" + resp.data;
        carUpdate.value.carAvatar = resp.data;
    }
}
//定义方法：查询所有停车场及车辆信息并显示修改的对话框
function showUpdateDialog(carId) {
    parklotApi.selectAll()
        .then(resp => {
            parklotList.value = resp.data;
            carApi.selectByCarId(carId)
                .then(resp => {
                    carUpdate.value = resp.data;
                    updateDialogShow.value = true;
                    imageUrlUpdate.value = `http://localhost:8080/upload/${carUpdate.value.carAvatar}`;
                });
        });
}
//定义方法：删除车辆信息
function deleteCar(carId) {
    carApi.delete(carId)
        .then(resp => {
            if (resp.code == 10000) {
                ElMessage.success(resp.msg);
                selectByPage(1);
            } else {
                ElMessage.error(resp.msg);
            }
        })
}
//定义方法：添加车辆
function insert() {
    carApi.insert(carAdd.value)
        .then(resp => {
            if (resp.code == 10000) {
                ElMessage.success(resp.msg);
                addDialogShow.value = false;
                //清空对话框中的内容
                carAdd.value = {
                    carPlate: '',
                    ownerName: '',
                    carType: '',
                    inTime: '',
                    outTime: '',
                    parkFee: '',
                    parkId: '',
                    carAvatar: ''
                };
                //imageUrl
                imageUrlAdd.value = '';
                //查询第一页
                selectByPage(1);
            } else {
                ElMessage.error(resp.msg);
            }
        });
}
//定义方法：图片上传之前的回调（判断是否可以上传）
function beforeAvatarUpload(rawFile) {
    if (rawFile.type !== 'image/jpeg') {
        ElMessage.error('图片格式错误，仅支持JPG格式')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('图片大小不能超过2M')
        return false
    }
    return true
}
//定义方法：添加图片上传成功的回调
function handleAvatarSuccessAdd(resp, uploadFile) {
    if (resp.code == 10000) {
        ElMessage.success(resp.msg);
        imageUrlAdd.value = "http://localhost:8080/upload/" + resp.data;
        carAdd.value.carAvatar = resp.data;
    }
}


//定义方法：查询所有停车场并显示添加的对话框
function showAddDialog() {
    parklotApi.selectAll()
        .then(resp => {
            parklotList.value = resp.data;
            addDialogShow.value = true;
        });
}
//定义方法：分页查询
function selectByPage(pageNum) {
    carApi.selectByPage(pageNum, ownerName.value)
        .then(resp => {
            console.log(resp);
            pageInfo.value = resp.data;
        });
}
//定义方法:查询第一页
selectByPage(1);
</script>

<style scoped>
.avatar-uploader,
.avatar {
    width: 178px;
    height: 178px;
    display: block;
    border: 1px dotted #dcdfe6;
    border-radius: 5px;
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>